package com.demo.component.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.log4j.Log4j2;

import java.util.*;

@Log4j2
public final class JsonUtil {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    public static String toJson(Object payload) {

        String payloadAsString = "";
        try {
            payloadAsString = objectMapper.writer().writeValueAsString(payload);
        } catch (JsonProcessingException e) {
            log.error("JsonUtil.toJson: Cannot deserialize payload to JSON {}", e.getMessage());
        }

        return payloadAsString;
    }

    public static Object getValueFromJsonStringByPath(String payload, List<String> path) {

        String valueNotFoundMessage = "Cannot fetch value for path {}";

        try {

            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);

            Map<String, Object> current = mapper.readValue(payload, new TypeReference<>() {});

            for (int i = 0; i < path.size(); i++) {

                String key = path.get(i);

                // If element in path is null, or it doesn't contain key - return empty response
                if (current == null || !current.containsKey(key)) {
                    log.warn(valueNotFoundMessage, path);
                    return "";
                }

                // Once we exhaust all path steps - return value of last element
                if (i == path.size() - 1) {
                    return current.get(key);
                }

                // Drill one level down and proceed with next key in path
                current = (Map<String, Object>) current.get(key);

            }

        } catch (Exception ex) {
            log.error(valueNotFoundMessage, path);
        }

        return "";

    }

}
